/*

依赖于momment.js
日历样式定义在common/widget/calendar.css

*/
function Calendar(dom,options){
    this.test = "";
    this.wrapper = $(dom);
    this.id = $(dom).attr('id');
    this.settings = $.extend(defaults, options, {});
    this._selectedDay = "";
    this._departDatesInfoMap = {};
    
    this._initData();
    this._init();
    if(this.settings.displayMonthes == 1){
        if(this.settings.enableHeaderAction == true){
            this._renderOne();
            this._bindHeaderEvent();
        }else{
            this._renderOneWithOutAction();
        }
        
        this._bindCellEvent();
    }else if(this.settings.displayMonthes > 1){
        this._renderMore(this.settings.displayMonthes);
        this._bindCellEvent();
    }
}


Calendar.prototype._renderOne = function(){
    this.container.find('.bt-c-week').remove();
    this.container.append(this.header);
    if(this.wrapper.find('.bt-c-body').length > 0){
        this.wrapper.find('.bt-c-body').remove();
    }
    this.container.append($(this.bodyTitle + this.bodyContent + this.bodyFooter));
    this.wrapper.append(this.container);
    this.wrapper.find('.bt-c-title').text(this.moment.get('year') + ' 年 ' + ( this.moment.month() + 1 ) + ' 月');
};

Calendar.prototype._renderOneWithOutAction = function(){
    this.container.find('.bt-c-week').remove();
    this.container.append(this.headerMore);
    if(this.wrapper.find('.bt-c-body').length > 0){
        this.wrapper.find('.bt-c-body').remove();
    }
    this.container.append($(this.bodyTitle + this.bodyContent + this.bodyFooter));
    this.wrapper.append(this.container);
    this.wrapper.find('.bt-c-title').text(this.moment.get('year') + ' 年 ' + ( this.moment.month() + 1 ) + ' 月');
};

Calendar.prototype._renderMore = function(num){
    for(var i=0; i<num; i++){
        this.container.append(this.headerMore.clone());
        this.bodyContent = this._drawDays();
        this.container.append($(this.bodyTitle + this.bodyContent + this.bodyFooter));
        this.container.find('.bt-c-title').eq(i).text(this.moment.get('year') + ' 年 ' + ( this.moment.month() + 1 ) + ' 月');
        this.moment.add('M',1);
    }
    this.wrapper.append(this.container);
};

Calendar.prototype._bindHeaderEvent = function(){
    var self = this;
    // 上个月和下个月
    if(self.moment.isBefore(self.settings.minDate, 'days')||self.moment.isSame(self.settings.minDate, 'days')){
        $('span.icon-arrow-left').hide();
    };
    if(self.moment.add('M',1).isAfter(self.settings.maxDate, 'days')){
        $('span.icon-arrow-right').hide();
    };
    self.moment.subtract('M',1);
    
    this.wrapper.find('.icon-arrow-left').click(function(e){
        if(self.moment.isBefore(self.settings.minDate, 'days')||self.moment.isSame(self.settings.minDate, 'days')){
            
        }else{
            self.moment.subtract('M',1 );
            self.bodyContent = self._drawDays();
            self._renderOne();
            self._bindCellEvent();
            if(self.moment.isBefore(self.settings.minDate, 'days')||self.moment.isSame(self.settings.minDate, 'days')){
                $('span.icon-arrow-left').hide();
            };
            if(self.moment.add('M',1).isBefore(self.settings.maxDate, 'days')||self.moment.isSame(self.settings.maxDate, 'days')){
                $('span.icon-arrow-right').show();
            };
            self.moment.subtract('M',1);     
        }
    });

    this.wrapper.find('.icon-arrow-right').click(function(e){
        if(self.moment.add('M',1).isAfter(self.settings.maxDate, 'days')){
            self.moment.subtract('M',1 );
        }else{
            //self.moment.add('M',1);
            self.bodyContent = self._drawDays();
            self._renderOne();
            self._bindCellEvent(); 
            $('span.icon-arrow-left').show();
            if(self.moment.add('M',1).isAfter(self.settings.maxDate, 'days')){
                $('span.icon-arrow-right').hide();
            };
            self.moment.subtract('M',1);
        }  
    });
};

Calendar.prototype._bindCellEvent = function(){
    var self = this;
    // 格子的点击事件（选中和取消选中）
    // 如果涉及到选择模式（多选和单选）在这里进行 todo:用事件委派可以提高性能
    this.wrapper.find('td').each(function(i,n){
        if(!$(n).hasClass('disabled')){
            $(n).click(function(e){
                $(this).addClass('selected');
                self._selectedDay = $(this).attr('data-date');// todo：在团期有价格的情况下，取值有问题
                $(this).siblings().removeClass('selected');
                $(this).parent().siblings().children().removeClass('selected');
                $(this).parents('.bt-c-body').siblings('.bt-c-body').find('td').removeClass('selected');
                self.settings.afterPickedDate(self);
            });
        }
    });
};

Calendar.prototype._init = function(){
    this.moment = moment(this.settings.currentDate);
    
    this.container = $('<div class="bt-calendar"></div>');
    this.header = $('<div class="bt-c-header"><span class="icon-arrow-left"><i></i></span><span class="bt-c-title"></span><span class="icon-arrow-right"><i></i></span></div>');
    this.headerMore = $('<div class="bt-c-header"><span class="bt-c-title"></span></div>');
    this.bodyTitle = '<div class="bt-c-body"><table>'+
                        '<tr class="bt-c-week"><th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th></tr>';
    this.bodyContent = this._drawDays();
    this.bodyFooter = '</table></div>';
};

Calendar.prototype._initData = function(){
    var self = this;
    if(this.settings.departDatesInfo.length > 0){
        $.each(this.settings.departDatesInfo, function(i,n){
            var date = n.start,
                title = n.title;
            self._departDatesInfoMap[date] = title;
        });
    }
};

Calendar.prototype._drawDays = function(){
    this.moment.startOf('month');
    var m = this.moment.month();
    var stopFlag = false;
    var w = '';
    for(var i=0; i<6; i++){
        var s = '<tr>';
        for(var j=0; j<7; j++){
            var weekday = this.moment.isoWeekday() == 7 ? 0 : this.moment.isoWeekday();
            if(weekday == j){
                // 如果月份大于本月
                if(this.moment.month() > m || (m == 11 && this.moment.month() === 0)){
                    this.moment.subtract('d',1);
                    // 如果日期为最后一天且是该表格行最后一个，就不要再另起一行计算了
                    if(j === 0){
                        stopFlag = true;
                        break;
                    }
                    stopFlag = true;
                    s += '<td class="disabled overdue"><div class="bt-content-wrapper"></div></td>';
                }else{
                    s = this._insertTD(s);
                    this.moment.add('d',1);
                }
            }else{
                s += '<td class="disabled overdue"><div class="bt-content-wrapper"></div></td>';
            }
        }
        s += '</tr>';
        w += s;
        if(stopFlag){
            if(this.moment.month() > m || (m == 11 && this.moment.month() === 0)){
                this.moment.subtract('d',1);
            }
            this.moment.date(1);
            break;
        }
    }
    return w;
};

Calendar.prototype._insertTD = function(s){
    // 这里是主要的显示日历格子的算法
    // 包含了对最小可选日期、最大可选日期的支持
    // 包含了对价格日历显示的支持
    var date = this.moment.get('date'),
        fullDate = this.moment.format("YYYY-MM-DD");
    if(this.settings.minDate && this.settings.maxDate && (this.moment.isBefore(this.settings.minDate, 'days') || this.moment.isAfter(this.settings.maxDate, 'days'))){
        s += '<td class="disabled" data-date='+fullDate+'><div class="bt-content-wrapper"><div class="date">'+date+'</div></div></td>';
    }else if(this.settings.departDatesInfo.length > 0){
        var self = this;
        var departFlag = false;
        var departTitle = {};

        if(self._departDatesInfoMap[fullDate]){
            departFlag = true;
            var titleStrArr = self._departDatesInfoMap[fullDate].split(',');
            departTitle = {
                price : titleStrArr[0],
                stock : titleStrArr[1]
            }
        }

        if(departFlag){
            // 可选团期的显示
            s += '<td data-date='+fullDate+'><div class="bt-content-wrapper"><div class="date">'+date+'</div><div class="price">'+departTitle.price+'</div><div class="stock">剩余:'+departTitle.stock+'</div></div></td>';
        }else{
            s += '<td class="disabled" data-date='+fullDate+'><div class="bt-content-wrapper"><div class="date">'+date+'</div></div></td>';
        }
    }else{
        s += '<td data-date='+fullDate+'><div class="bt-content-wrapper"><div class="date">'+date+'</div></div></td>';
    }
    return s;
};

// 获取选中的日期
Calendar.prototype.getSelectedDay = function(){
    return this._selectedDay;
};

// 设置当前日期,并触发回调
Calendar.prototype.setSelectedDay = function(date){
    var newDate = moment(date).format('YYYY-MM-DD');
    this.wrapper.find('td[data-date="'+newDate+'"]').trigger('click');
};

var defaults = {
    currentDate:moment(), //默认显示时间
    minDate:"",
    maxDate:"",
    departDatesInfo:[],//必须是在minDate和maxDate范围之内
    displayMonthes:1,// 显示的月数，默认为1
    enableHeaderAction:true, //当displayMonthes为1时，是否启用向前向后按钮
    afterPickedDate: function(o){
       console.log(o.getSelectedDay());
    }
};

window.BT = window.BT || {};
BT.Calendar = Calendar;